//
// Ishtar C++ Utility Library
//
// Task Facility - Work Poller Implementation
//

#include <Ishtar/Pch.h>

#include <Ishtar/Chrono/TimedBool.h>
#include <Ishtar/Task/WorkPollerImpl.h>


namespace Ishtar
{

namespace Task
{

///////////////////////////////////////////////////////////////////////////////
//
// Work Poller
//

void WorkPollerImpl::Shutdown()
{
}


void WorkPollerImpl::Submit( const WorkImplPtr& w )
{
    w->Start( this );
}


void WorkPollerImpl::AddReadyWork( const WorkImplPtr& w )
{
    m_readyWorks.Push( w );
}


Uint WorkPollerImpl::Process( Uint sliceTime )
{
    TimedBool slice;
    if ( 0 != sliceTime )
    {
        slice.Start( sliceTime );
    }

    Uint count = 0;
    WorkImplPtr work;
    while ( !slice && m_readyWorks.TryPop( work ))
    {
        ++ count;
        work->Run();
    }

    return count;
}


//
// Bridging
//

WorkPoller::WorkPoller()
    : m_impl( new WorkPollerImpl )
{}


WorkPoller::~WorkPoller()
{}


void WorkPoller::Shutdown()
{
    m_impl->Shutdown();
}


void WorkPoller::Submit( const Work& w )
{
    if ( w.IsEmpty() ) { return; }

    m_impl->Submit( w.m_impl );
}


Uint WorkPoller::GetNumWorks() const
{
    return m_impl->GetNumWorks();
}


Uint WorkPoller::GetNumReadyWorks() const
{
    return m_impl->GetNumReadyWorks();
}


Uint WorkPoller::Process( Uint sliceTime )
{
    return m_impl->Process( sliceTime );
}


///////////////////////////////////////////////////////////////////////////////

} // namespace Task

} // namespace Ishtar
